package org.apache.commons.graph.model

import org.apache.commons.graph.Graph
import org.apache.commons.graph.Mapper
import org.apache.commons.graph.SpanningTree
import org.apache.commons.graph.bean.DefaultEdge
import org.apache.commons.graph.weight.Monoid

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

/**
 * A memory-based implementation of a mutable spanning tree.
 *
 * This class is NOT thread safe!
 *
 * @param <V> the Graph vertices type
 * @param <WE> the Graph weighted edges type
 * @param <W> the weight type
</W></WE></V> */
class MutableSpanningTree<V, WE, W>(
    private val weightOperations: Monoid<W>,
    private val weightedEdges: Mapper<WE, W>
) : UndirectedMutableGraph<V, WE>(), SpanningTree<V, WE, W> {
    /**
     * {@inheritDoc}
     */
    override var weight: W
        private set

    /**
     * Creates a new instance of [MutableSpanningTree]
     *
     * @param weightOperations
     * @param weightedEdges
     */
    init {
        this.weight = weightOperations.identity()
    }

    /**
     * {@inheritDoc}
     */
    override fun decorateAddEdge(head: V, e: WE, tail: V) {
        super.decorateAddEdge(head, e, tail)
        weight = weightOperations.append(weight, weightedEdges.map(e))
    }

    /**
     * {@inheritDoc}
     */
    override fun decorateRemoveEdge(e: WE) {
        weight = weightOperations.append(weight, weightOperations.inverse(weightedEdges.map(e)))
    }

}

fun<V, WE, W> Graph.Companion.mutableSpanningTree(
         weightOperations: Monoid<W>,
         weightedEdges: Mapper<WE, W>
) = MutableSpanningTree<V, WE, W>(weightOperations, weightedEdges)


fun<V, W> Graph.Companion.sampleMutableSpanningTree(
    weightOperations: Monoid<W>,
    weightedEdges: Mapper<DefaultEdge<V>, W>
) = MutableSpanningTree<V,DefaultEdge<V> ,W>(weightOperations, weightedEdges)